# -*- coding: utf_8 -*-
# @Create   : 2021/8/18 14:16
# @Author   : yh
# @Remark   : 视频组管理

from mxsoftpy import Server
from mxsoftpy.exception import DataError

from db.common.VideoManage.VideoQuality.video_group import VideoGroupDB
from db.common.VideoManage.VideoQuality.video import VideoDB
from model.common.VideoManage.VideoQuality.video_group import VideoGroupModel, VideoUpdateModel
from utils.public.data_process import list_to_trees
from utils.public.params_method import pro_decode


class VideoGroupServer(Server):
    __model__ = VideoGroupModel
    __db__ = VideoGroupDB

    def list(self, s_code: str) -> dict:
        """
        获取视频组列表
        param: s_code 查询类型
        return: v_type 数据类型  0：组 1：视频
        """
        group_dict = self.db.group_dict()
        res = dict()
        for k, v in group_dict.items():
            res[k] = {'code': k, 'name': v.get('name'), 'parent_code': v.get('parent_code'),'v_type': 0}
        total = len(group_dict)
        if s_code == "1":  # 如果s_code为“1”时，查询到视频层
            video_list = VideoDB().group_select(state=1, order_by='create_time')
            for video in video_list:
                video['code'] += '_'
                res[video['code']] = video
                total = len(video_list)
        try:
            data_list = list_to_trees(res, parent_value="0")
        except KeyError:
            raise DataError('数据异常，无法生成视频组节点树')
        base_mun = [{
            'code': "0",
            'name': '全部',
            'parent_code': '',
            'v_type': 0,
            'children': data_list
        }]

        res_dict = {
            "data": base_mun,
            "total": total
        }
        return res_dict

    def delete(self, group_code: str) -> dict:
        """
        删除视频组
        :param group_code: 视频组code
        """
        return self.db.delete(group_code)

    def update(self, group_code: str, **video_update_model: str) -> str:
        """
        更新视频组
        :param group_code: 视频组code
        :param video_update_model: 新的名称
        """
        video_update_model = pro_decode(**video_update_model)

        return self.db.update(group_code, **VideoUpdateModel(**video_update_model).dict())

    def select(self, name: str) -> dict:
        """
        根据关键词查询视频组
        :param name: 查询关键词
        """
        data_list = list()
        group_dict = self.db.select(name)
        for k, v in group_dict.items():
            data_list.append({'code': k, 'name': v.get('name')})
        res_dict = {
            "data": data_list,
            "total": len(data_list)
        }
        return res_dict

    def create(self, **params):
        """
        新建视频组
        """
        group_params = pro_decode(**params)
        res = self.db.create(**group_params)
        res_dict = {'group_code': res}
        return res_dict
